package org.alfalfa.exception;

import org.alfalfa.exception.model.BizError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author : Max-Goday
 * @Created : 2016-09-30
 * @E-mail : goday.max@gmail.com
 * @Version : 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	public static final String DEFAULT_ERROR_VM = "error";

	@ExceptionHandler(value = Exception.class)
	public ModelAndView _default(HttpServletRequest request, Exception e) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", e);
		mav.addObject("url", request.getRequestURL());
		mav.setViewName(DEFAULT_ERROR_VM);

		return mav;
	}

	@ExceptionHandler(value = BizException.class)
	@ResponseBody
	public BizError<String> bizException(HttpServletRequest request, BizException e) {

		BizError<String> error = new BizError<>();
		error.setMessage(e.getMessage());
		error.setCode(BizError.ERROR);
		error.setData("This is error data");
		error.setUrl(request.getRequestURL().toString());

		return error;

	}

}
